#!/usr/bin/perl

package Utils;

use strict;
use warnings;

use Data::Dumper;
use POSIX qw(strftime);
use JSON;
use Carp qw(croak);

use Exporter 'import';
our @EXPORT_OK = qw(
    dd 
    date 
    in_array array_empty is_array 
    hash_key_exists 
    kebab_to_camel camel_to_kebab
    json_decode 
);

# 打印变量的类型和内容
# 示例：
# my $test = 1;
# dd($test);
# 输出：
# ==== File /Users/dd/Documents/Perl/app.pl Line 19 ====
# Var type is: SCALAR
# $VAR1 = 1;
sub dd
{
    my ($var) = @_;
    require Data::Dumper;
    print "| -> File: ". (caller(0))[1] ." line ". (caller(0))[2] .".\n";
    print "|    Caller: [". (caller(1))[1] ."]\n";
    print "|    Var type is: ". (ref($var) || 'SCALAR'). "\n";
    print "|    " . Data::Dumper::Dumper($var);
}

# 格式化当前时间
# 示例：
# print date(). "\n";
# print date(time(), '%Y-%m-%d'). "\n";
# 输出：
# 2024-04-20 16:30:00
# 2024-04-20
sub date
{
    my ($time, $format) = @_;
    $time = time() if!defined($time);
    $format = '%Y-%m-%d %H:%M:%S' if!defined($format);
    return strftime($format, localtime($time));
}

sub is_array
{
    my ($var) = @_;
    return ref($var) eq 'ARRAY';
}

# 判断数组是否包含某个值
# 示例：
# my @test = (1, 2, 3);
# if(in_array(2, @test)) {
#     print "2 is in array\n";
# } else {
#     print "2 is not in array\n";
# }
# 输出：2 is in array
sub in_array
{
    my ($value, @array) = @_;
    for my $item (@array) {
        return 1 if $item eq $value;
    }
    return 0;
}

# 判断数组是否为空
# 示例：
# my @test = (1, 2, 3);
# if(array_empty(@test)) {
#     print "array is empty\n";
# } else {
#     print "array is not empty\n";
# }
# 输出：array is not empty
sub array_empty
{
    my ($array) = @_;
    return 1 if !defined($array) || !@$array;
    return 0;
}

# 下划线转大驼峰
# 示例：
# print kebab_to_camel("hello-world"). "\n";
# 输出：HelloWorld
sub kebab_to_camel {
    my ($str) = @_;
    my @parts = split('-', $str);
    my $camel_str = '';
    foreach my $part (@parts) {
        $part = ucfirst(lc($part));
        $camel_str .= $part;
    }
    return $camel_str;
}

# 大驼峰转下划线
# 示例：
# print camel_to_kebab("HelloWorld"). "\n";
# 输出：hello-world
sub camel_to_kebab {
    my ($str) = @_;
    my $kebab_str = '';
    my $prev_char = '';
    foreach my $char (split(//, $str)) {
        if ($prev_char =~ /[A-Z]/ && $char =~ /[A-Z]/) {
            $kebab_str.= '-';
        }
        $kebab_str.= lc($char);
    }
    return $kebab_str;
}

# 解析JSON字符串转哈希表
# 示例：
# my $json = '{"name": "John", "age": 30, "city": "New York"}';
# my %hash = json_decode($json);
sub json_decode
{
    my $json = shift;
    unless (defined $json) {
        return {};
    }
    return JSON::decode_json($json);
}

# 获取文件内容
# 示例：
# my @lines = get_file_content("test.txt");
sub get_file_content
{
    my $file = shift;
    open(my $fh, '<', $file) or croak "Could not open file '$file' $!";
    my @lines = <$fh>;
    close($fh);
    return @lines;
}

1;

__END__
